#include "XThread.h"
#include <windows.h>

struct XThread
{
	HANDLE		mHandle;
	HANDLE		mThreadID;
	BOOL		mCreateSuspended;
	BOOL		mTerminated;
	BOOL		mSuspended;
	BOOL		mFinished;
	ThreadFunc	mExecuteFunc;
};

struct XThread* CreateXThread(ThreadFunc executeFunc, enum XTHREAD_CREATE_FLAG createFlag)
{
	struct XThread *newThread = malloc(sizeof(struct XThread));
	memset(newThread, 0, sizeof(struct XThread));
	newThread->mExecuteFunc = executeFunc;
	newThread->mHandle = CreateThread(NULL, 
										0, 
										executeFunc, 
										newThread, 
										0, 
										(LPDWORD)&newThread->mThreadID);
	return newThread;
}

void ResumeXThread(struct XThread* thread)
{
	thread->mSuspended = FALSE;
	ResumeThread(thread->mHandle);
}

void SuspendXThread(struct XThread* thread)
{
	BOOL oldSuspend = thread->mSuspended;
	thread->mSuspended = TRUE;
	if(SuspendThread(thread->mHandle) >= 0)
		thread->mSuspended = oldSuspend;	
}

void TerminateXThread(struct XThread* thread)
{
	thread->mTerminated = TRUE;
}

unsigned long WaitForXThread(struct XThread* thread)
{
	unsigned long exitCode = 0;
	WaitForSingleObject(thread->mHandle, INFINITE);
	GetExitCodeThread(thread->mHandle, &exitCode);
	return exitCode;
}

void DestroyXThread(struct XThread* thread)
{
	if(thread)
	{
		if(thread->mHandle != NULL)
			CloseHandle(thread->mHandle);
		free(thread);
	}
}
